package com.smedi.ismedi.cronjob.core.domain.service.impl;

import com.smedi.ismedi.cronjob.core.domain.aggregatemodel.JobInfo;
import com.smedi.ismedi.cronjob.core.domain.repository.JobInfoRepository;
import com.smedi.ismedi.cronjob.core.domain.service.JobService;
import lombok.AllArgsConstructor;
import org.quartz.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class JobServiceImpl implements JobService {
    private JobInfoRepository cronjobRepository;

    @Override
    public JobDataMap getJobDataMap(JobInfo jobInfo) {
        JobDataMap map = new JobDataMap();
        map.put("id", jobInfo.getId());
        map.put("name", jobInfo.getName());
        map.put("jobGroup", jobInfo.getJobGroup());
        map.put("cronExpression", jobInfo.getCronExpression());
        map.put("parameter", jobInfo.getParameter());
        map.put("jobDescription", jobInfo.getDescription());
        map.put("serviceName", jobInfo.getServiceName());
        map.put("type", jobInfo.getType());
        map.put("jobUrl", jobInfo.getUrl());
        map.put("status", jobInfo.getPause());
        return map;
    }

    @Override
    public List<JobInfo> findAll() {
        return cronjobRepository.doList();
    }

    @Override
    public JobDetail getJobDetail(JobKey jobKey, String description, JobDataMap map) {
        return JobBuilder.newJob(JobImpl.class)
                .withIdentity(jobKey)
                .withDescription(description)
                .setJobData(map)
                .storeDurably()
                .build();
    }

    //获取Trigger (Job的触发器,执行规则)
    @Override
    public Trigger getTrigger(JobInfo jobInfo) {
        return TriggerBuilder.newTrigger()
                .withIdentity(jobInfo.getName(), jobInfo.getJobGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(jobInfo.getCronExpression()))
                .build();
    }

    //获取JobKey,包含Name和Group
    @Override
    public JobKey getJobKey(JobInfo jobInfo) {
        return JobKey.jobKey(jobInfo.getName(), jobInfo.getJobGroup());
    }
}
